package com.zmx.gateway.config;

import com.zmx.gateway.utils.JacksonUtil;
import com.zmx.gateway.utils.SimpleBitMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Description: 用户黑名单缓存
 * @ClassName: MemberBlacklistCacheConfig
 * @Author zhaomxr
 * @Date 2022-01-14 10:19
 */
@Slf4j
@Component
public class MemberBlacklistCacheConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    private Integer lock = 1;
    private String BLACKLISTCACHE_KEY = "blacklist";
    private String BLACKLISTCACHE_UPDATE_KEY = "blacklist_update";
    private static SimpleBitMap blacklistCache = null;

    /**
     * 如果当前黑名单静态实例不存在且redis中没有更新标识，那么刷新当前黑名单
     * @return
     */
    private SimpleBitMap getBlacklistCache() {
        Object update = redisTemplate.opsForValue().get(BLACKLISTCACHE_UPDATE_KEY);
        if (blacklistCache == null || update != null) {
            synchronized (lock) {
                if (blacklistCache == null || update != null) {
                    Object object = redisTemplate.opsForValue().get(BLACKLISTCACHE_KEY);
                    //如果缓存中没有最新的黑名单数据，那么理解返回空，交由网关过滤器走数据库查询
                    if (object != null) {
                        blacklistCache = JacksonUtil.jsonStringToBean(object.toString(),SimpleBitMap.class);
                    } else {
                        return null;
                    }
                    return blacklistCache;
                }
            }
        }
        return blacklistCache;
    }

    public SimpleBitMap get() {
        return getBlacklistCache();
    }

    public boolean contain(String id) {
        SimpleBitMap simpleBitMap = getBlacklistCache();
        if (simpleBitMap.contain(Integer.valueOf(id))) {
            return true;
        }
        return false;
    }
}
